import { View } from '@tarojs/components';
import Taro, {  useLoad } from '@tarojs/taro';
import {Form, Button, Cell, Loading, Navbar, Field, Input, Avatar} from '@taroify/core';
import { UserCircleOutlined } from '@taroify/icons';
import { useDispatchUser, useUserSelector } from "@/hooks/user";
import { useState } from "react";
import {uploadFile} from "@/api/upload";
import './index.css';


export default function UserInfo() {
  const dispatchUser = useDispatchUser();
  const userDetail = useUserSelector(state => state.user.user);
  const [avatarSrc, setAvatarSrc] = useState(userDetail?.avatar || ''); // 头像
  const [nickname, setNickname] = useState(userDetail?.nickname || ''); // 昵称
  const [apiKey, setAPIKey] = useState(userDetail?.email || ''); // 简介
  // const [email, setEmail] = useState(userDetail?.email || ''); // 简介
  // const [phone, setPhone] = useState(userDetail?.phone || ''); // 简介
  const [loading, setLoading] = useState(false); // 加载状态

  useLoad(() => {
    dispatchUser.fetchUser();
    console.log('Page loaded.');
  });

  const windowInfo = Taro.getWindowInfo();
  const statusBarHeight = windowInfo.statusBarHeight;

  // 提交表单
  const handleSubmit = () => {
    if(userDetail){
      setLoading(true);
      const updatedUser = {
        avatar: avatarSrc,
        nickname,
      };
      dispatchUser.updateUser(userDetail.username, updatedUser);
      setLoading(false);
    }
  };

  const returnProfilePage = async () => {
    await Taro.redirectTo({
      url: '/pages/tabs/profile/index',
    });
  };

  const onChooseAvatar = async (e) => {
    const res = await uploadAvatar(e.detail.avatarUrl)
    setAvatarSrc(res.url)
  }

  // 上传头像到服务器
  const uploadAvatar = async (file) => {
    return await uploadFile(file);
  }

  return (
    <View style={{ height: '100vh', width: '100vw', backgroundColor: 'white' }}>
      {/* 导航栏 */}
      <Navbar
        style={{
          paddingTop: `${(statusBarHeight || 0) + 50}rpx`,
          background: 'linear-gradient(-225deg, #2CD8D5 0%, #C5C1FF 56%, #FFBAC3 100%)',
          boxShadow: '0 2rpx 10rpx rgba(0, 0, 0, 0.1)',
        }}
      >
        <Navbar.NavLeft onClick={returnProfilePage} style={{color: 'black'}} />
        <Navbar.Title style={{ fontSize: '35rpx', color: 'black', fontWeight: 'bold' }}>
          个人资料
        </Navbar.Title>
      </Navbar>

      {/* 表单内容 */}
      <View style={{ width: '100%', height: `calc(100% - ${(statusBarHeight || 0) + 180}rpx)`, overflowY: 'auto' }}>
        {userDetail ? (
          <Form>
            {/* 头像 */}
            <Cell.Group>
              <Field
                label='头像'
              >
                  <Button
                    open-type='chooseAvatar'
                    onChooseAvatar={onChooseAvatar}
                    style={{border: '0'}}
                  >
                    {avatarSrc ? <Avatar src={`${process.env.TARO_APP_BASE_URL}${avatarSrc}`} /> :<UserCircleOutlined size={40} />}
                  </Button>
              </Field>

              <Field label='昵称'>
                <Input
                  type='nickname'
                  value={nickname}
                  className='info-content__input'
                  placeholder='请输入昵称'
                  onChange={(e) => setNickname(e.detail.value)}
                />
              </Field>

              {/*<Field label='密钥'>*/}
              {/*  <Input placeholder='请输入密钥' value={apiKey} onChange={(e) => setAPIKey(e.detail.value)} />*/}
              {/*</Field>*/}

              {/*<Field label='邮箱'>*/}
              {/*  <Input placeholder='请输入邮箱' value={email} onChange={(e) => setEmail(e.detail.value)} />*/}
              {/*</Field>*/}

              {/*<Field label='号码'>*/}
              {/*  <Input placeholder='请输入号码' value={phone} onChange={(e) => setPhone(e.detail.value)} />*/}
              {/*</Field>*/}
            </Cell.Group>

            {/* 提交按钮 */}
            <View style={{ padding: '40rpx' }}>
              <Button
                block
                color='primary'
                loading={loading}
                onClick={handleSubmit}
              >
                保存
              </Button>
            </View>
          </Form>
        ) : (
          <Loading type='spinner' />
        )}
      </View>
    </View>
  );
}
